<template>
  <el-dialog
    title="历史限流配置列表"
    :visible.sync="visible"
    width="65%"
    top="10vh"
    :before-close="closeDialogHandle"
    :close-on-click-modal="false"
    append-to-body
  >
    <el-table
      v-loading="dataLoad"
      element-loading-text="历史限流配置列表加载中..."
      element-loading-spinner="el-icon-loading"
      :data="limitConfigList"
      ref="limitConfigTable"
      :row-class-name="tableRowClassName"
    >
      <el-table-column prop="requestKey" header-align="center" align="center" label="接口路径" width="150"></el-table-column>
      <el-table-column prop="type" header-align="center" align="center" label="限流类型">
        <template v-slot="{row}">
          {{ row.type | baseFormat(typeEnumList) }}
        </template>
      </el-table-column>
      <el-table-column prop="timeNum" header-align="center" align="center" label="时间数值"></el-table-column>
      <el-table-column prop="timeType" header-align="center" align="center" label="单位" >
        <template v-slot="{row}">
          {{ row.timeType | baseFormat(timeTypeEnumList) }}
        </template>
      </el-table-column>
      <el-table-column prop="maxNum" header-align="center" align="center" label="最大次数" ></el-table-column>
      <el-table-column prop="limitTime" header-align="center" align="center" label="限流时长（秒）" width="120"></el-table-column>
      <el-table-column prop="version" header-align="center" align="center" label="版本号"></el-table-column>
      <el-table-column prop="status" header-align="center" align="center" label="状态" width="65">
        <template v-slot="{row}">
          {{ row.status | baseFormat(statusEnumList) }}
        </template>
      </el-table-column>
      <el-table-column prop="createUser" header-align="center" align="center" label="创建用户"></el-table-column>
      <el-table-column
        header-align="left"
        width="130"
        label="操作">
        <template v-slot="{ row }">
          <el-button type="text" icon="el-icon-view" @click="$refs.viewDialog.initDialog(row)">
            查看
          </el-button>
          <el-button v-if="row.status === 1" type="text" icon="el-icon-check" @click="useLimitConfigHandle(row)">
            启用
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      hide-on-single-page
      :disabled="dataLoad"
      :current-page="searchForm.page"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="searchForm.limit"
      :total="totalNum"
      layout="total, sizes, prev, pager, next, jumper"
      class="paging">
    </el-pagination>

    <span slot="footer" class="dialog-footer">
      <el-button @click="closeDialogHandle">关 闭</el-button>
    </span>

    <!-- 查看限流配置弹出框 -->
    <view-dialog :type-enum-list="typeEnumList" :time-type-enum-list="timeTypeEnumList"
                 :status-enum-list="statusEnumList" ref="viewDialog" />
  </el-dialog>
</template>

<script>
  import ViewDialog from "@/components/limit/view";
  export default {
    name: "limit-config-history-dialog",
    components: {
      ViewDialog
    },
    props: {
      // 限流类型枚举列表
      typeEnumList: {
        type: Array,
        default: () => []
      },
      // 时间枚举列表
      timeTypeEnumList: {
        type: Array,
        default: () => []
      },
      // 状态枚举列表
      statusEnumList: {
        type: Array,
        default: () => []
      },
    },
    data() {
      return {
        // 弹出框显示状态[true-显示 false-关闭]
        visible: false,
        // 点击的数据行主键
        id: undefined,
        // 历史限流配置数据列表
        limitConfigList: [],
        // 历史限流配置检索表单对象
        searchForm: {
          // 接口路径
          word: '',
          // 限流类型[0-请求 1-异常]
          type: '',
          // 当前展示页码
          page: 1,
          // 当前页显示个数
          limit: 10,
        },
        // 限流配置总数
        totalNum: 0,
        // 数据加载状态[false-不加载 true-加载]
        dataLoad: false,
      }
    },
    filters: {
      /**
       * 枚举映射方法
       * @param {number} value 参数值
       * @param {Array} list  枚举列表
       */
      baseFormat(value, list) {
        for (let obj of list) {
          if (obj.value === value) {
            return obj.name;
          }
        }
        return '未知';
      }
    },
    methods: {
      /**
       * 初始化弹出框方法
       * @param {string} id         主键
       * @param {string} requestKey 接口路径
       * @param {number} type       限流类型
       */
      initDialog(id, requestKey, type) {
        this.id = id;
        let _searchForm = this.searchForm;
        _searchForm.word = requestKey;
        _searchForm.type = type;

        this.getPageLimitConfigList();

        this.visible = true;
      },
      /**
       * 启用限流配置事件
       * @param {Object} limitConfig 限流配置对象
       */
      useLimitConfigHandle(limitConfig) {
        // 按钮禁用
        this.buttonLoad = true;
        this.$axios.$post('/sys/limit-config/check', limitConfig)
          .then(({ data }) => {
            let message = '您确定要启用限流配置吗?'
            if (data.checkFlag) {
              // 校验拒绝
              message = '已存在可用的限流配置数据，是否要新增限流配置，停用旧的限流配置?'
            }
            return this.$confirm(message, '操作提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            });
          })
          .then(() => {
            let data = {
              id: limitConfig.id,
              requestKey: limitConfig.requestKey,
              type: limitConfig.type
            }
            return this.$axios.$post('/sys/limit-config/use', data);
          })
          .then(() => {
            this.notify('success', '操作成功', '启用限流配置操作成功');

            // 刷新列表
            this.getPageLimitConfigList();
          })
          .catch(() => {})
          .finally(() => {
            // 按钮恢复可用
            this.buttonLoad = false;
          })
      },
      /**
       * 分页获取限流配置方法
       */
      getPageLimitConfigList() {
        // 开始数据加载
        this.dataLoad = true;
        this.$axios.$post('/sys/limit-config/history/page/list', this.searchForm)
          .then(({ data }) => {
            this.limitConfigList = data.data;
            this.totalNum = data.totalNum;
          })
          .catch(() => {})
          .finally(() => {
            // 数据加载结束
            this.dataLoad = false;
          })
      },
      /**
       * 每页显示个数变化事件
       * @param {number} size 最新显示个数值
       */
      sizeChangeHandle(size) {
        let searchForm = this.searchForm;
        searchForm.page = 1;
        searchForm.limit = size;
        this.getPageLimitConfigList()
      },
      /**
       * '点击特定页码'、'上一页'、'下一页'操作事件
       * @param {number} index 最新页码
       */
      currentChangeHandle(index) {
        let searchForm = this.searchForm;
        if (searchForm.page === index) {
          return
        }
        searchForm.page = index
        this.getPageLimitConfigList()
      },
      /**
       * 关闭弹出框方法
       */
      closeDialogHandle() {
        this.visible = false;
        // 清理数据
        this.limitConfigList = [];
        this.searchForm = {
          requestKey: '',
          type: '',
          page: 1,
          limit: 10
        }
        this.totalNum = 0;
      },
      /**
       * 高亮表格行方法
       * @param row       行数据对象
       * @param rowIndex  行号
       * @return {string} css样式名称
       */
      tableRowClassName({row, rowIndex}) {
        if (row.id === this.id) {
          return 'success-row';
        }
        return '';
      }
    }
  }
</script>

<style scoped>
  .el-table >>> .success-row {
    background: #f0f9eb;
  }
  .paging {
    float: right;
    margin: 7px;
  }
</style>
